<?php

namespace PinWuYun\Controller;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use PinWuYun\domain\helper\OrderHelper;
use PinWuYun\domain\service\commonServer\SyncService;
use PinWuYun\domain\service\messageServer\ActionFactory;
use PinWuYun\domain\service\starLinkServer\CallBack;
use PinWuYun\domain\service\starLinkServer\Config;
use PinWuYun\domain\service\youZanServer\LogServer;
use Slim\Http\Request;
use Slim\Http\Response;

class IndexController extends BaseController
{

    /**
     * @throws Exception
     */
    public function index(Request $request, Response $response, $args): Response
    {
        return $response->withJson(['json' => 'test']);
    }

    /**
     * 同步商品数据
     * @return string
     * @throws GuzzleException
     */
    public function sync(): string
    {
        try {
            return (new SyncService)->syncGoodsAll();
        } catch (Exception $e) {
            LogServer::errLog($e);
            return $e->getMessage();
        }

    }

    /**
     * 更新商品数据
     * @throws GuzzleException
     */
    public function updateGoods(): string
    {
        try {
            return (new SyncService)->updateGoodsAll();
        } catch (Exception $e) {
            LogServer::errLog($e);
            return $e->getMessage();
        }
    }

    /** 有赞支付通知 -》 星链下单 -》 星链发货(starCallBack) -》 有赞确认发货 -》 有赞交易完成 -》 星链确认收货 */

    /**
     * 星链回调接口
     * @throws Exception
     */
    public function starCallBack(Request $request)
    {
        try{
            /**  消息来源验证 */
            $params = $request->getParams();
            $state = (new CallBack)->run($params);
            /**  获取有赞订单号 */
            switch ($state) {
                // 卖家发货
                case Config::CONFIRMED_RECEIVE:
                    (new OrderHelper)->sendGoodsAction($params);
                    break;
                // 交易完成
                case Config::TRADE_FINISH:
                    (new OrderHelper)->sendTradeFinishAction($params);
                    break;
                default:
                    // TODO
                    break;
            }
            return 'success';
        } catch (Exception | GuzzleException $e) {
            LogServer::save($e);
            return 'fail';
        }
    }

    /**
     * 有赞消息接受接口
     * @throws Exception
     */
    public function yzMsgCallBack(Request $request)
    {

        try{
            $params = $request->getParams();
            /**  消息来源验证 TODO */

            /** 判断消息类型，分开处理 */
            return ActionFactory::getAction($params['type'])->doAction($params);
        } catch (Exception $e) {
            LogServer::errLog($e);
            return $e->getMessage();
        }

    }




}